package biz.ezcom.spring.jdbc.dao.impl;

import java.sql.Types;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import biz.ezcom.spring.jdbc.dao.IUserDao;
import biz.ezcom.spring.jdbc.po.User;

public class UserDao
    implements IUserDao {
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int insertUser(User user, boolean needId) {
        String sql = "INSERT INTO user (role_id,username,password,birthday) VALUES(?,?,?,?)";
        Object[] parameters = new Object[] {user.getRoldId(), user.getUsername(), user.getPassword(), user.getBirthday()};
        int[] types = new int[] {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.DATE};
        int insertCount = jdbcTemplate.update(sql, parameters, types);
        if(needId) {
            int id = jdbcTemplate.queryForInt("SELECT LAST_INSERT_ID()");
            user.setId(id);
        }
        return insertCount;
    }

    @Override
    public int deleteUser(int id) {
        String sql = "DELETE FROM user where id=?";
        Object[] parameters = new Object[] {id};
        int[] types = new int[] {Types.INTEGER};
        int deleteCount = jdbcTemplate.update(sql, parameters, types);
        return deleteCount;
    }

    @Override
    public int updateUserById(User user) {
        String sql = "UPDATE user SET role_id=?,username=?,password=?,birthday=? where id=?";
        Object[] parameters = new Object[] {user.getRoldId(), user.getUsername(), user.getPassword(), user.getBirthday(), user.getId()};
        int[] types = new int[] {Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.DATE, Types.INTEGER};
        int updateCount = jdbcTemplate.update(sql, parameters, types);
        return updateCount;
    }

    @Override
    public User selectUser(int id) {
        String sql = "SELECT id,role_id,username,password,birthday from user where id=?";
        Object[] parameters = new Object[] {id};
        int[] types = new int[] {Types.INTEGER};
        SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql, parameters, types);
        if (rowSet.next()) {
            User user = new User();
            user.setId(rowSet.getInt("id"));
            user.setRoldId(rowSet.getInt("role_id"));
            user.setUsername(rowSet.getString("username"));
            user.setPassword(rowSet.getString("password"));
            user.setBirthday(rowSet.getDate("birthday"));
            return user;
        } else {
            return null;
        }
    }
}
